package de.baumann.browser.activitys.gg

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import de.baumann.browser.R
import de.baumann.browser.adapter.ExtractTransAdapter
import de.baumann.browser.api.net.vo.gg.ExtractTrans
import de.baumann.browser.api.net.vo.gg.GGMain
import de.baumann.browser.base.BaseOdinActivity
import de.baumann.browser.db.ETHWallet
import de.baumann.browser.iview.gg.IRansomView
import de.baumann.browser.present.gg.RansomPresenter
import de.baumann.browser.utils.TimeUtil
import de.baumann.browser.utils.web3j.TokenUtil
import de.baumann.browser.views.dialog.PayPwdDialog
import kotlinx.android.synthetic.main.activity_g_ransom.*
import kotlinx.android.synthetic.main.include_tool_bar.*
import java.math.BigDecimal
import java.util.*

class GRansomActivity : BaseOdinActivity<IRansomView, RansomPresenter>(), IRansomView {

    companion object {
        fun startGRansomActivity(context: Context, ggMain: GGMain, wallet: ETHWallet) {
            context.startActivity(Intent(context, GRansomActivity::class.java).apply {
                val bundle = Bundle().apply {
                    putSerializable("ggMain", ggMain)
                    putSerializable("wallet", wallet)
                }
                putExtras(bundle)
            })
        }
    }

    private var mortgage: BigDecimal = BigDecimal(0)
    private lateinit var extractTransAdapter: ExtractTransAdapter

    override fun getLayout(): Int {
        return R.layout.activity_g_ransom
    }

    override fun getTitleText(): String {
        return "Ransom"
    }

    private var payPwdDialog: PayPwdDialog? = null
    override fun initView() {
        initToolbar(commToolBar, commTitle)

        extractTransAdapter = ExtractTransAdapter()
        rvExtractTrans.adapter = extractTransAdapter

        btnWithdraw.setOnClickListener {
            val calendar = Calendar.getInstance()
            calendar.timeInMillis = getGGMain().createTimeLong
            if (getGGMain().type == 2) {
                calendar.add(Calendar.MONTH, 12)
            } else {
                calendar.add(Calendar.MONTH, getGGMain().month)
            }

            val time = calendar.time.time
            if (System.currentTimeMillis() < time) {
                showShortToast("can not ransom")
                return@setOnClickListener
            }

            if (mortgage <= BigDecimal(0)) {
                showShortToast("Mortgage ODIN error, please go back and try again")
                return@setOnClickListener
            }

            if (getGGMain().type == 2 && count != BigDecimal(0)) {
                showShortToast("Number of mortgage addresses > 0 ,can not ransom")
                return@setOnClickListener
            }
            showPwdDialog()
        }
    }

    private fun showPwdDialog() {
        payPwdDialog = PayPwdDialog(mContext, object : PayPwdDialog.PwdCallback {
            override fun callback(pwd: String) {
                try {
                    val privateKey = TokenUtil.getPrivateKey(pwd, getWallet())
                    if (getGGMain().type == 2) {
                        presenter?.b021(privateKey, mortgage.toString())
                    } else {
                        presenter.b02(privateKey, mortgage.toString())
                    }
                } catch (e: Exception) {
                    if ("Invalid password provided" == e.message) {
                        Toast.makeText(mContext, "Invalid Password", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(mContext, e.message, Toast.LENGTH_SHORT).show()
                    }
                }
            }
        })
        payPwdDialog!!.show()
    }

    override fun initData() {
        val address = getUserAddress()
        if (address.startsWith("0x")) {
            userAddress.text = "od${address.substring(1)}"
        } else {
            userAddress.text = address
        }

        mortgageTime.text = TimeUtil.getStringByFormat(getGGMain().createTimeLong, "yyyy-MM-dd HH:mm:ss")
        val duration: Int
        if (getGGMain().type == 2) {
            duration = 12
            tvSmelter.visibility = View.VISIBLE
            rlSmelter.visibility = View.VISIBLE
            presenter?.b011()
        } else {
            duration = getGGMain().month

        }

        mortgageDuration.text = "$duration months"
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = getGGMain().createTimeLong
        calendar.add(Calendar.MONTH, duration)
        val time = calendar.time.time
        ransomTime.text = TimeUtil.getStringByFormat(time, "yyyy-MM-dd HH:mm:ss")
        presenter?.b01()
        presenter?.b04()
    }


    override fun getSmelterAddress(): String {
        if (getGGMain().type == 2) {
            return getUserAddress()
        }
        return getGGMain().userAddress
    }

    override fun getUserAddress(): String {
        return getWallet().getAddress()
    }


    override fun setMortgageNum(mortgage: BigDecimal) {
        this.mortgage = mortgage
        mortgageNum.text = mortgage.toString()
    }

    private var count: BigDecimal = BigDecimal(-1)
    override fun setUserCount(count: BigDecimal) {
        this.count = count
        mortgagePNum.text = count.toString()
    }

    override fun ransomSuccess() {
        payPwdDialog?.dismiss()
        showShortToast("Request Success")
        setResult(Activity.RESULT_OK)
        finish()
    }

    override fun setExtracts(data: List<ExtractTrans>) {
        extractTransAdapter.addData(data)
    }

    override fun createPresenter(): RansomPresenter {
        return RansomPresenter()
    }

    override fun createView(): IRansomView {
        return this
    }

    private fun getGGMain(): GGMain {
        return intent.getSerializableExtra("ggMain") as GGMain
    }

    private fun getWallet(): ETHWallet {
        return intent.getSerializableExtra("wallet") as ETHWallet
    }
}